package sq.sms;

import com.aliyuncs.exceptions.ClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sq.dao.VerificationInfo;
import sq.repository.VerificationRepository;
import sq.util.VerificationCodeImpl;

import java.util.Date;

/**
 * @Author BianYang
 */
@Service
public class SqSmsVlidator implements SmsVlidator {
    private static Logger logger = LoggerFactory.getLogger(SqSmsVlidator.class);
    @Autowired
    private TplSmsSender tplSmsSender;
    @Autowired
    private VerificationCodeImpl verificationCodeImpl;
    @Autowired
    private VerificationRepository verificationRepository;
    @Value("${templateCode}")
    public String templateCode;
    private String vCode = "";
    private String vPhone = "";

    @Override
    public String sendValidation(String phone) {
        vCode = verificationCodeImpl.getVerificationCode();
        vPhone = phone;
        try {
            tplSmsSender.send(phone, templateCode, "{\"code\":\"" + vCode + "\"}");
        } catch (ClientException e) {
            logger.error("1.客户端丢失.如处在无人区;2.阿里服务器抛出异常,导致客户端未接收到短信;3.手机号无效,无法接收短信", e);
        }
        verificationRepository.save(new VerificationInfo(phone, vCode, new Date()));
        return vCode;
    }

    /**
     * 确定此验证码是此手机发送出来的
     *
     * @param phone 开发者用户手机号
     * @param code  验证码
     * @return boolean 布尔值
     */
    @Override
    public boolean validate(String phone, String code) {
        boolean isValidCodeValue = code != null && code.equals(vCode);
        boolean isNotEmptyValue = !"".equals(vCode) && !"".equals(vPhone);
        boolean isValidPhoneValue = (phone != null && phone.equals(vPhone));
        return isValidCodeValue && isNotEmptyValue && isValidPhoneValue;
    }
}